﻿using AvaloniaNotes.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;

namespace AvaloniaNotes.AvaloniaNotesDBContext
{
    public class NoteDBContext : DbContext
    {
        public DbSet<Note> Notes { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlite("FileName=./Note.db");
            base.OnConfiguring(optionsBuilder);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Note>(entity =>
            {
                entity.ToTable(nameof(Note));
                entity.Property(x=>x.NoteId).HasColumnName("Id").IsRequired();
                entity.Property(x => x.Content).IsRequired();
                entity.Property(x => x.Color).IsRequired();
                entity.Ignore(x => x.BtnColor);
            });

            base.OnModelCreating(modelBuilder);
        }

        public override int SaveChanges()
        {
            //添加操作
            ChangeTracker.Entries().Where(e => e.State == EntityState.Added).ToList()
                .ForEach(e => ((Note)e.Entity).CreatedTime = DateTime.Now);

            //修改操作
            ChangeTracker.Entries().Where(e => e.State == EntityState.Modified ).ToList()
                .ForEach(e => ((Note)e.Entity).UpdatedTime = DateTime.Now);
            return base.SaveChanges();
        }
    }
}
